package com.gxkj.drm.interceptor;

import com.gxkj.drm.constant.WebConstant;
import com.gxkj.drm.entitys.PushUser;


import com.gxkj.drm.util.AccessUtil;
import com.gxkj.drm.util.LoginHelper;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Created by changxiangyang on 2017/9/19.
 */
public class ValidateIntercepter extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //查看是否有权利访问请求资源
        PushUser user = LoginHelper.getLoginUser(request);
        if(AccessUtil.checkPermission(user, handler)) {
            return true;
        }

        //非法请求 即这些请求需要登录后才能访问
        //重定向到登录页面
        response.sendRedirect(WebConstant.PAGE_LOGIN);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (modelAndView != null) {
            String viewName = modelAndView.getViewName();
            if (WebConstant.PAGE_HOME.equals(viewName)) {
                PushUser user = LoginHelper.getLoginUser(request);
                if (user != null) {
                    // 返回用户等级和用户名页眉显示
                    Map<String, Object> model = modelAndView.getModel();
                    model.put("level", user.getLevel());
                    model.put("nickName", user.getNickName());
                }
            }
        }
    }

}
